import {
  getWrokingHoursOverViewByPage,
  addWrokingHoursOverView,
  updateWrokingHoursOverView,
  delWrokingHoursOverView,
  exportWrokingHoursOverView,
  getWorkingHoursCountByPage,
} from '@/services/product/wrokingHoursOverView';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Tree } from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import moment from 'moment';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import dayjs from 'dayjs';
const WrokingHoursOverView: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();
  const ref = useRef(null);
  //日期格式
  const dateFormat = 'YYYY-MM';
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      hideInTable: true,
      width: 80,
      align: 'center',
      sorter: true,
    },

    {
      title: '月份',
      dataIndex: 'createTime',
      align: 'center',
      sorter: true,
      valueType: 'date',
      render: (text, record) => {
        return <span>{dayjs(record.currStartTime).format(dateFormat)}</span>;
      },
    },
    {
      title: '人员',
      dataIndex: 'personnelName',
      align: 'center',
      sorter: true,
    },
    {
      title: '实际任务工时',
      dataIndex: 'actualTaskWorkhour',
      align: 'center',
      sorter: true,
      render: (text, record) => {
        return record.actualTaskWorkhour ? text : 0;
      },
    },
    {
      title: '实际项目填报工时',
      dataIndex: 'actualProjectWorkhour',
      align: 'center',
      sorter: true,
      render: (text, record) => {
        return record.actualProjectWorkhour ? text : 0;
      },
    },
    {
      title: '实际工单填报工时',
      dataIndex: 'actualWoWorkhour',
      align: 'center',
      sorter: true,
      render: (text, record) => {
        return record.actualWoWorkhour ? text : 0;
      },
    },
    {
      title: '实际总工时',
      dataIndex: 'sumWorkHours',
      align: 'center',
      sorter: true,
      render: (text, record) =>
        record.actualTaskWorkhour + record.actualProjectWorkhour + record.actualWoWorkhour,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      render: (text, record, _, action) => [
        // <a
        //   key="editKey"
        //   onClick={() => {
        //     setModalVisit(true);
        //     setCreateOrUpdate(true);
        //     setFormTitle('编辑');
        //     form.setFieldsValue({
        //       accWorkHours: record.accWorkHours,
        //       currStartTime: record.currStartTime,
        //       operatorId: record.operatorId,
        //       processId: record.processId,
        //       sumWorkHours: record.sumWorkHours,
        //       timeFlag: record.timeFlag,
        //       id: record.id,
        //     });
        //   }}
        // >
        //   编辑
        // </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delWrokingHoursOverView({ id: record.id });
                actionRef.current.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const handleSubmit = async (values) => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      const result = await addWrokingHoursOverView(values);
      if (result != null) {
        message.success('添加成功');
      }
    } else {
      await updateWrokingHoursOverView(values);
    }
    setConfirmLoading(false);
    setModalVisit(false);
    actionRef.current.reload();
  };

  return (
    <div>
      <ProTable
        headerTitle="个人工时报表统计查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={{ labelWidth: 'auto' }}
        toolBarRender={(action, { selectedRows }) => [
          // <Button
          //   key="button"
          //   icon={<PlusOutlined />}
          //   onClick={() => {
          //     setCreateOrUpdate(false);
          //     setFormTitle('新建');
          //     form.resetFields();
          //     setModalVisit(true);
          //   }}
          //   type="primary"
          // >
          //   新建
          // </Button>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              const filters = filterTran(ref.current.getFieldsValue());
              exportWrokingHoursOverView({
                current: 1,
                pageSize: 5000,
                filters: filters,
              }).then((res) => {
                const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);
                aLink.setAttribute('download', `WrokingHoursOverView.xlsx`);
                aLink.click();
                document.body.removeChild(aLink);
              });
            }}
            type="primary"
          >
            导出
          </Button>,
        ]}
        pagination={{
          defaultCurrent: 1,
          defaultPageSize: 100,
          showSizeChanger: true,
          pageSizeOptions: ['100', '500', '1000'],
        }}
        request={async (params = {}, sort, filter) => {
          const sorters = sortTran(sort);
          const filters = filterTran(params);
          const result = await getWorkingHoursCountByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 1500, y: 350 }}
        rowSelection={{}}
      />

      <ModalForm
        visible={modalVisit}
        title={formTitle}
        form={form}
        onFinish={handleSubmit}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
        <ProFormText
          name="accWorkHours"
          label="当前累计工时"
          rules={[{ required: true, message: 'Please input your accWorkHours!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="currStartTime"
          label="本次计时开始时间"
          rules={[{ required: true, message: 'Please input your currStartTime!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="operatorId"
          label="操作人"
          rules={[{ required: true, message: 'Please input your operatorId!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="processId"
          label="工序ID"
          rules={[{ required: true, message: 'Please input your processId!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="sumWorkHours"
          label="当前工序总累计工时"
          rules={[{ required: true, message: 'Please input your sumWorkHours!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="timeFlag"
          label="计时开关"
          rules={[{ required: true, message: 'Please input your timeFlag!' }]}
          disabled={createOrUpdate}
        />
      </ModalForm>
    </div>
  );
};
export default WrokingHoursOverView;
